<template>
  <div class="app-container">
    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="800px" v-dialogDrag append-to-body>
      <el-form ref="formRef" :model="formData" :rules="formRules" v-loading="formLoading" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="仓库名称" prop="warehouseName">
              <el-input v-model="formData.warehouseName" placeholder="请输入仓库名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="父级仓库" prop="parentId">
              <treeselect
                v-model="formData.parentId"
                :options="warehouseTree"
                :normalizer="normalizerW"
                placeholder="选择父级仓库"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="仓库编码" prop="warehouseCode">
              <el-input v-model="formData.warehouseCode" placeholder="请输入仓库编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="仓库类型" prop="warehouseType">
              <el-select v-model="formData.warehouseType" placeholder="请选择仓库类型" filterable style="width: 100%">
                <el-option v-for="dict in this.getDictDatas(DICT_TYPE.WARE_TYPE)" :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工厂/车间" prop="plantId">
              <treeselect v-model="formData.plantId" :options="deptList" :normalizer="normalizer" placeholder="选择所属部门" style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否开启" prop="freezeStatus">
              <el-radio-group v-model="formData.freezeStatus">
                <el-radio v-for="dict in this.getDictDatas(DICT_TYPE.COMMON_STATUS)" :key="parseInt(dict.value)"
                          :label="parseInt(dict.value)"
                >
                  {{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="formLoading">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as WarehouseApi from '@/api/storage/warehouse';
import { getDictDatas, getDictDataLabel, DICT_TYPE } from '@/utils/dict';
import Treeselect from '@riophae/vue-treeselect';
import '@riophae/vue-treeselect/dist/vue-treeselect.css';
import { listDept } from '@/api/system/dept';

// 导入工厂/车间相关API（假设使用部门API获取工厂/车间数据）
// 如果有专门的工厂/车间API，可以替换为相应的API

export default {
  name: 'WarehouseForm',
  components: {
    Treeselect
  },
  data() {
    return {
      // 弹出层标题
      dialogTitle: '',
      // 是否显示弹出层
      dialogVisible: false,
      // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
      formLoading: false,
      // 表单参数
      formData: {
        id: undefined,
        warehouseName: undefined,
        parentId: undefined,
        warehouseCode: undefined,
        warehouseType: undefined,
        freezeStatus: undefined,
        plantId: undefined,
      },
      // 表单校验
      formRules: {
        warehouseName: [{ required: true, message: '仓库名称不能为空', trigger: 'blur' }],
        freezeStatus: [{ required: true, message: '仓库冻结状态不能为空', trigger: 'blur' }],
        plantId: [{ required: true, message: '工厂/车间不能为空', trigger: 'blur' }],
      },
      // 仓库树数据
      warehouseTree: [],
      // 工厂/车间列表
      deptList: [],
      // 是否为顶级节点（用于禁用父级选择）
      isTopLevelNode: false
    };
  },
  methods: {
    /** 打开弹窗 */
    async open(data) {
      this.dialogVisible = true;
      this.reset();

      // 加载仓库树和工厂/车间列表
      await Promise.all([this.getWarehouseTree(), this.getdeptList()]);

      // 修改时，设置数据
      if (data && data.id) {
        // 直接使用传入的数据，不需要再次调用接口获取详情
        this.formData = { ...data };
        this.dialogTitle = '编辑仓储仓库';

        // 检查是否为顶级节点
        this.isTopLevelNode = !this.formData.parentId || this.formData.parentId === 0;
      } else {
        this.dialogTitle = '新增仓储仓库';
      }
    },

    /** 获取仓库树数据 */
    async getWarehouseTree() {
      try {
        const params = {
          pageNo: 1,
          pageSize: 1000 // 获取足够多的数据用于构建树
        };
        const res = await WarehouseApi.getWarehousePage(params);
        // 处理树结构，确保有正确的格式
        const processedTree = res.data

        // 在最外层添加一个"无"节点，id为0
        this.warehouseTree = [{
          id: 0,
          warehouseName: '无',
          children: processedTree,
          // 设置为禁用状态，这样用户只能选择其子节点
          disabled: false
        }];
      } catch (error) {
        console.error('获取仓库树数据失败:', error);
        this.$modal.msgError('获取仓库树数据失败');
      }
    },

    /** 获取工厂/车间列表 */
    async getdeptList() {
      try {
        const response = await listDept();
        this.deptList = this.handleTree(response.data, "id")[0].children;
      } catch (error) {
        console.error('获取部门列表失败', error);
      }
    },

    /** 树节点标准化处理 */
    normalizerW(node) {
      const normalizedNode = {
        id: node.id,
        label: node.warehouseName,
        // 只有当children存在且不为空数组时才传递children属性
        // 这样没有子节点的节点就不会显示展开按钮
        children: node.children && node.children.length > 0 ? node.children : undefined
      };

      // 如果是根节点("无")，设置为不可选择
      if (node.id === 0) {
        normalizedNode.disabled = true;
      }

      return normalizedNode;
    },
    normalizer(node) {
      // 构建基础对象，确保包含 id, label, children 属性
      const normalizedNode = {
        id: node.id,
        label: node.name,
        children: node.children, // 必须包含 children
      };

      // 关键：如果不是第三级节点，则禁用
      return normalizedNode;
    },
    /** 处理树结构数据 */
    /** 处理树结构数据 */


      // 递归构建子节点


    /** 提交按钮 */
    async submitForm() {
      // 校验主表
      await this.$refs['formRef'].validate();
      this.formLoading = true;
      try {
        const data = this.formData;
        // 修改的提交
        if (data.id) {
          await WarehouseApi.updateWarehouse(data);
          this.$modal.msgSuccess('修改成功');
          this.dialogVisible = false;
          this.$emit('success');
          return;
        }
        // 添加的提交
        await WarehouseApi.createWarehouse(data);
        this.$modal.msgSuccess('新增成功');
        this.dialogVisible = false;
        this.$emit('success');
      } finally {
        this.formLoading = false;
      }
    },

    /** 表单重置 */
    reset() {
      this.formData = {
        id: undefined,
        warehouseName: undefined,
        parentId: undefined,
        warehouseCode: undefined,
        warehouseType: undefined,
        freezeStatus: 0, // 默认设置为0（未冻结状态）
        plantId: undefined,
      };
      this.isTopLevelNode = false;
      this.resetForm('formRef');
    }
  }
};
</script>
